<template>
  <el-dialog
    v-bind="$attrs"
    width="1000px"
    :title="dialogForm.id ? '修改角色' : '新增角色'"
    center
  >
    <el-form
      ref="dialogFormRef"
      :model="dialogForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="dialogForm.name" />
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input v-model="dialogForm.code" />
      </el-form-item>
      <el-form-item label="是否默认组织" prop="isDefault">
        <el-radio-group v-model="dialogForm.isDefault">
          <el-radio label="1">是</el-radio>
          <el-radio label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择应用名称" prop="applicationId">
        <el-select
          v-model="dialogForm.applicationId"
          placeholder="请选择应用名称"
          clearable
          filterable
        >
          <el-option
            v-for="item in appNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onclose()">取消</el-button>
        <el-button type="primary" @click="submit(false)" v-if="isDetail"
          >修改</el-button
        >
        <el-button type="primary" @click="submit(true)" v-if="!isDetail">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  reactive,
  ref,
  toRefs,
  watch,
  computed,
  onMounted,
} from "vue";
import Editor from "@/components/Editor/index.vue";
import { apiUrl } from "@/api/api";
import axios from "axios";
import { ElMessage } from "element-plus";

export default defineComponent({
  components: { Editor },
  props: {
    dataForm: Object,
    isDetail: {
      type: Boolean,
      default: false,
    },
    isFabu: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { emit }) {
    const dialogFormRef = ref();
    const dataMap = reactive({
      dialogForm: {
        id: "", // 添加选中的应用名称字段
        isDefault: "0",
      },
      appNameOptions: [],
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        // applicationId: [
        //   { required: true, message: "请输入应用ID", trigger: "blur" },
        // ],
        code: [{ required: true, message: "请输入编码", trigger: "blur" }],
        applicationId: [
          { required: true, message: "请选择应用名称", trigger: "change" },
        ],
      },
    });

    // 如果需要从接口获取应用名称列表
    const fetchAppNames = () => {
      axios({
        method: "post",
        url: apiUrl.baseUrl + "/wl/auth/application/getList",
        data: {},
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
          loginToken: sessionStorage.getItem("loginToken"),
        },
      })
        .then((response) => {
          dataMap.appNameOptions = response.data.data.data.map((item) => ({
            value: item.id, // or whatever unique identifier
            label: item.applicationName, // the property that contains the display name
          }));
        })
        .catch((error) => {
          console.log(error);
        });
    };

    const methodsMap = reactive({
      onclose() {
        emit("close");
      },
      submit(flag) {
        if (flag) {
          dialogFormRef.value.validate((valid) => {
            if (valid) {
              let data = {};
              data = dataMap.dialogForm;
              data.parentId = "0";
              let params = {};
              params.data = data;
              params.rid = "";
              axios({
                method: "post",
                url: apiUrl.baseUrl + "/wl/auth/identity/create",
                data: params,
                headers: {
                  "Content-Type": "application/json;charset=UTF-8",
                  loginToken: sessionStorage.getItem("loginToken"),
                },
              })
                .then((response) => {
                  if (response.data.code === "-1") {
                    ElMessage.error(response.data.message);
                  } else {
                    setTimeout(() => {
                      emit("getDatas");
                      emit("close");
                    }, 500);
                  }
                })
                .catch((error) => {});
            } else {
              return;
            }
          });
        } else {
          dialogFormRef.value.validate((valid) => {
            if (valid) {
              let data = {};
              data = dataMap.dialogForm;
              let params = {};
              params.data = data;
              params.rid = "";
              axios({
                method: "post",
                url: apiUrl.baseUrl + "/wl/auth/identity/save",
                data: params,
                headers: {
                  "Content-Type": "application/json;charset=UTF-8",
                  loginToken: sessionStorage.getItem("loginToken"),
                },
              })
                .then((response) => {
                  setTimeout(() => {
                    emit("getDatas");
                    emit("close");
                  }, 500);
                })
                .catch((error) => {});
            } else {
              return;
            }
          });
        }
      },
    });

    onMounted(() => {
      fetchAppNames(); // 获取应用名称列表
      if (props.dataForm) {
        let temp = JSON.parse(JSON.stringify(props.dataForm));
        dataMap.dialogForm = {
          ...temp,
          parentId: temp.parentId || "",
          isDefault: temp.isDefault,
        };
      }
    });

    return {
      ...toRefs(dataMap),
      ...toRefs(methodsMap),
      dialogFormRef,
    };
  },
});
</script>
